// pages/search_2/search_2.js
var n = 1;
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    istypeclass:false,//是否点击分类进来的
    inputs: "",
    amout: false,
    loading: false,
    allLoaded: true,
    goload: false,
    goods: [],
    order_by: "",
    order_field: "",
    showGoodScreen: false,

    brandId: "",
    filterId: [],
    classifyBol: true,
    zoneId: '',
    coupon: '',
    showcccc: false,
    activeName: '1',
    plugin_id: 0,

    btnFlag: false, // 回到顶部
    btnData: {
      "button_size": 40,
      "over_top": 500,
      "position_location": "right",
      "icon_url": ""
    },

    machineId:"",//自动售货机id

    showHistory: false, // 显示搜索历史
    deliverId: null,
    point:{},
    requestLoading: true,
    searchScreen: {},//筛选条件
    yzSupplyLease:false,
    pluginType:'',
    pluginShow:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    // typestring
    if(options.id!=""&&!isNaN(options.id)){
      this.setData({['searchScreen.typestring']:options.id,istypeclass:true});
      wx.setNavigationBarTitle({ title: '分类列表' });
    }
    console.log(options,'ddddddd');
    try {
      const value = wx.getStorageSync('zoneId');
      if (value) {
        this.setData({
          zoneId: value
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
    if (options.fromPage) {
      this.setData({
        fromPage: options.fromPage
      });
    }
    if (options.kind) {
      this.setData({
        kind: 'kind'
      });
    }
    if (options.keyword) {
      this.setData({
        inputs: options.keyword
      });
    }
    if (options.order_field) {
      this.setData({
        order_field: options.order_field
      });
    }
    if (options.order_by) {
      this.setData({
        order_by: options.order_by
      });
    }
    if (options.coupon) {
      this.setData({
        coupon: options.coupon
      });
    }
    if (options.as_id) {
      this.setData({
        zoneId: options.as_id
      });
    }
    if (options.brand_id) {
      this.setData({
        ['searchScreen.brandId']: options.brand_id
      });
    }
    if (options.plugin_id == 1) {
      this.setData({
        plugin_id: options.plugin_id
      });
    }
    if(options.machineId){
      this.setData({machineId:options.machineId})
    }
    if(options.isYzSupple){
      this.setData({
        yzSupplyLease:true,
        region_id:options.region_id,
      })
    }
    if (options.product_attr) {
      let attrStr = options.product_attr.split(",");
      let attr = this.data.attr ? this.data.attr : [];
      for (let i = 0; i < attrStr.length; i++) {
        for (let k = 0; k < attr.length; k++) {
          if (attr[k].rot == attrStr[i]) {
            this.setData({
              ['attr[' + k + '].show']: false
            });
            break;
          }
        }

      }
      this.setData({
        attrStr
      });
    }
    if (options.filtering) {
      let filterId = options.filtering.split(",");
      filterId = filterId.map((i) => {
        return parseInt(i);
      });
      this.setData({
        ['searchScreen.filterId']: isNaN(filterId) ? undefined : filterId
      });
    }
    if (options.category) {
      this.setData({
        ['searchScreen.typestring']: options.category
      });
    }

    if (options.classificationParentIndex) {
      this.setData({
        classificationParentIndex: parseInt(options.classificationParentIndex),
        activeName: parseInt(options.classificationParentIndex)
      });
    }
    if (options.classificationId1) {
      this.setData({
        classificationId1: parseInt(options.classificationId1)
      });
    }
    if (options.classificationId2) {
      this.setData({
        classificationId2: parseInt(options.classificationId2)
      });
    }

    if (options.tmpl&& options.tmpl == 'dy') {
      //这是 自提点关联供应商 的分类，该分类页面只显示自提点关联的供应商的商品和平台商品（包含聚合供应链商品），其他供应商商品不显示，没有关联自提点的供应商商品也不显示。
      await this.getNowPackageDeliver();
    }
    if(options.tag) {
      this.setData({
        pluginType:options.tag
      })
    }
    this.search();
  },
  tapUpper() {
    if(this.data.inputs) {
      this.setData({
        inputs: ''
      });
      this.search();
    }
    try {
      wx.navigateBack({
        delta: 1,
        success: (res) => {},
        fail: (res) => {
          wx.reLaunch({
            url: '/packageG/index/index'
          });
        },
        complete: (res) => {},
      });
    } catch (error) {
      wx.reLaunch({
        url: '/packageG/index/index'
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.data.deliverId) this.getNowPackageDeliver();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.allLoaded) {
      n++;
      let loading = true;
      this.gotoSearch(n, loading);
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let urlStr = "";

    urlStr += "?keyword=" + this.data.inputs;
    urlStr += "&order_field=" + this.data.order_field;
    urlStr += "&order_by=" + this.data.order_by;
    urlStr += "&coupon=" + this.data.coupon;
    urlStr += "&as_id=" + this.data.zoneId;
    urlStr += "&brand_id=" + this.data.searchScreen.brandId;
    urlStr += "&product_attr=" + this.data.searchScreen.attrstr;
    urlStr += "&filtering=" + this.data.searchScreen.filterId;
    urlStr += "&category=" + this.data.searchScreen.typestring;
    urlStr += "&classificationParentIndex=" + this.data.classificationParentIndex;
    urlStr += "&classificationId1=" + this.data.classificationId1;
    urlStr += "&classificationId2=" + this.data.classificationId2;
    console.log(urlStr);
    return {
      path: "/packageB/member/category/search_v2/search_v2" + urlStr
    };
  },

  // 获取滚动条当前位置
  onPageScroll: function (e) {
    // 节流
    if (e.scrollTop > 80) {
      if (!this.data.btnFlag) {
        this.setData({
          btnFlag: true
        });
      }
    } else {
      if (this.data.btnFlag) {
        this.setData({
          btnFlag: false
        });
      }
    }
  },

  sortOut(e){
    console.log(e)
    let {order_by,order_field} = e.detail;
    this.setData({
      order_by,order_field
    });
    if (this.data.goods.length == 0) {
      return;
    }
    n = 1;
    this.setData({
      goods: []
    });
    this.gotoSearch(n);
  },
  search() {
    n = 1;
    this.setData({
      goods: [],
      goload: true
    });
    
    wx.showLoading({
      title:"加载中",
      mask: true //是否显示透明蒙层，防止触摸穿透
    })
    this.gotoSearch(n);

  },

  // 点击tag搜索
  serachTag(event) {
    let value = event.detail;
    this.setData({
      inputs: value
    });
    this.search();
  },
  gotoSearch(page = 1, loading = false) {
    // 添加搜索记录
    this.selectComponent("#search_history").appendKeywords(this.data.inputs);
    let that = this;
    let urlStr = "";
    if (this.data.fromPage == '1') {
      urlStr = app.getNetAddresss("plugin.pending-order.frontend.wholesale-area.goods-list");
    } else if(this.options.tmpl && this.options.tmpl == 'dy'){
      urlStr = app.getNetAddresss("plugin.supplier.frontend.category.search-goods");
    } else if(this.options.CommodityRights && this.options.CommodityRights == "CommodityRights"){
      urlStr = app.getNetAddresss("plugin.love-speed-pool.frontend.goods.getList");
    } else if(this.data.machineId){
      urlStr = app.getNetAddresss("plugin.automat.frontend.goods.searchGoods");
    } else if (this.options.tag === 'coffee'){
      urlStr = app.getNetAddresss("plugin.coffee-machine.frontend.goods.searchGoods")
    } else if (this.options.tag === 'collection-center'){
      urlStr = app.getNetAddresss("plugin.collection-center.frontend.controllers.goods.goods.index")
    } else if (this.options.tag === 'horizon'){
      urlStr = app.getNetAddresss("plugin.horizon.frontend.goods.searchGoods")
      if(this.options.machine_id){
        urlStr += "&machine_id=" + this.options.machine_id;
      }
      if(this.options.machine_type){
        urlStr += "&machine_type=" + this.options.machine_type;
      }
    } else if (this.options.tag == 'distributionCouponSearch'){
      urlStr = app.getNetAddresss("plugin.distribution-coupon.api.goods.search-goods")
      if(this.options.coupon_id){
        urlStr += "&coupon_id=" + this.options.coupon_id;
      }
    } else if (this.options.tag == 'cultivate_course'){
      urlStr = app.getNetAddresss("plugin.cultivate-course.frontend.controllers.goods.goods.search-goods")
      if(this.options.course_term_id){
        urlStr += "&course_term_id="+this.options.course_term_id
      }
    } else {
      urlStr = app.getNetAddresss("goods.goods.search-goods");
    }
    let price;
    if(this.data.searchScreen.top || this.data.searchScreen.mini){
      if(!this.data.searchScreen.mini){
        price = this.data.searchScreen.top
      }else{
        price = `${ this.data.searchScreen.mini }${ this.data.searchScreen.top ?','+this.data.searchScreen.top:this.data.searchScreen.top?this.data.searchScreen.top:'' }`
      }
    }
    urlStr += "&search[keyword]=" + this.data.inputs;
    urlStr += "&page=" + page;
    urlStr += "&order_field=" + this.data.order_field;
    urlStr += "&order_by=" + this.data.order_by;
    urlStr += "&search[couponid]=" + this.data.coupon;
    urlStr += "&search[as_id]=" + this.data.zoneId;
    urlStr += "&search[brand_id]=" + this.data.searchScreen.brandId;
    urlStr += "&search[product_attr]=" + this.data.searchScreen.attrstr;
    urlStr += "&search[filtering]=" + this.data.searchScreen.filterId;
    urlStr += "&search[category]=" + this.data.searchScreen.typestring;
    if(this.options.tag == 'coffee'){
      urlStr += "&search[coffee_machine_id]=" + this.options.machine_id;
    }
    if(price){
      urlStr += "&search[price_range]=" + price;
    }
    if (this.data.plugin_id == 1) {
      // 筛选平台商品
      urlStr += "&search[plugin_id]=0";
    }
    if(this.data.machineId){
      //自动售货机商品
      urlStr+='&automat_machine_id='+this.data.machineId + '&search[automat_machine_id]='+this.data.machineId
    }
    this.setData({
      requestLoading: true
    });
    if(this.data.yzSupplyLease){
      let yzSupplyArea;
      try {
        yzSupplyArea = wx.getStorageSync('yzSupplyArea');
      } catch (error) {}
      urlStr = '';
      // 租赁中台商品
      urlStr = app.getNetAddresss("plugin.yz-supply-lease.api.goods.goods-list");
      urlStr += "&page=" + page;
      urlStr += "&search[keyword]=" + this.data.inputs?this.data.inputs:'';
      urlStr += "&search[brand_id]=" + this.data.searchScreen && this.data.searchScreen.brandId?this.data.searchScreen.brandId:'';
      urlStr += "&search[supplier_id]=" + this.data.searchScreen && this.data.searchScreen.supplier_id?this.data.searchScreen.supplier_id:'';
      urlStr += "&search[cate]=" + this.data.searchScreen && this.data.searchScreen.typestring?this.data.searchScreen.typestrin:'';
      urlStr += "&search[region]=" + this.data.region_id ? this.data.region_id : (yzSupplyArea && yzSupplyArea.region_id ? yzSupplyArea.region_id : '');
      urlStr += "&sort[type]=" + this.data.order_field||'';
      urlStr += "&sort[direction]=" + this.data.order_by||'';
    }
    app._getNetWork({
      showToastIn: false,
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let datum = res.data;
          that.setData({
            loading: false,
            allLoaded: false
          });
          // 搜索结果为空
          if (datum?.data?.length <= 0 || datum?.goods_list?.length <= 0) {
            that.setData({
              loading: true,
              allLoaded: true
            });
            return;
          }
          // 如果当前页数大于总页数 就不加载了
          if (res.data.current_page > res.data.last_page || datum?.goods_list?.current_page > datum?.goods_list?.last_page) {
            that.setData({
              loading: true,
              allLoaded: true
            });
            return;
          }
          let goods = that.data.goods;
          if(that.data.pluginType == 'collection-center') {
            goods.push(...datum?.goods_list?.data);
            that.data.pluginShow = false;
          } else {
            goods.push(...res.data.data);
            that.data.pluginShow = true;
          }
          for (let i = 0; i < goods.length; i++) {
            if (parseInt(Number(goods[i].market_price == 0))) {
              goods[i].notMarket_price = 0;
            } else {
              goods[i].notMarket_price = 1;
            }
          }
          that.setData({
            goods: goods,
            pluginShow:that.data.pluginShow,
            requestLoading: false
          });
          try {
            that.setData({
              goods_template: res.data.goods_template,
              goods_style_set: res.data.goods_style_set
            });
          } catch (err) {
            console.log(err);
          }
          if (!loading) {
            if (that.data.goods_template&&(that.data.goods_template.names == '02' || that.data.goods_template.names == '03')) {
              that.setData({
                showcccc: true,
                classifyBol: false
              });
            }
          }
          if (datum?.data?.length < 15 || datum?.goods_list?.length < 15) {
            that.setData({
              loading: true,
              allLoaded: true
            });
            return;
          }
        }else{
          that.setData({
            requestLoading: false
          });
        }
      },
      fail: function (res) {
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },
  
  classifyBolbtn() {
    if (this.data.showcccc) {
      this.setData({
        showcccc: false,
        classifyBol: true
      });
    } else {
      this.setData({
        showcccc: true,
        classifyBol: false
      });
    }
  },
  inpbtn(e) {
    let val = e.detail.value;
    this.setData({
      inputs: val
    });
  },
  inpbtnclear() {
    this.setData({
      inputs: ''
    });
  },

  showbox() {
    this.setData({
      showGoodScreen: !this.data.showGoodScreen
    });
  },
  

  focusSearchInput() {
    this.setData({
      showHistory: true
    });
  },
  blurSerachInput() {
    this.setData({
      showHistory: false
    });
  },
  searchBlur() {
    this.setData({
      showHistory: false
    });
  },
  searchfocus() {
    this.setData({
      showHistory: true
    });
  },
  async getNowPackageDeliver() {
    //获取自提点信息
    let deliverIDStorage = null;
    try {
      deliverIDStorage = wx.getStorageSync('deliverId'); //获取当前会话是否存储了自提点id
    } catch (e) {
      // Do something when catch error
    }
    if(deliverIDStorage){
      //判断是否有在其他页面更新了自提点id,如果两个id一样则不需要更新请求接口
      if(this.data.deliverId&&this.data.deliverId!=deliverIDStorage){
        this.data.deliverId = deliverIDStorage;
        // 更换了自提点，请求更新数据
        this.search();
      }
      return true;
    }else if(!this.options.dyID){
      await this._asyncLocation();
    }

    wx.showLoading({
      title: "加载中",
      mask: true,
    });
    return new Promise((resolve, reject) => {
      let _json = {};
      if (this.data.point&&this.data.point.lng) {
        _json = {
          lng: this.data.point.lng||'',
          lat: this.data.point.lat||''
        };
      }
      if (this.options.dyID) {
        _json.deliver_id = this.options.dyID;
      }
      let urlStr = app.getNetAddresss('plugin.package-deliver.frontend.decorate-deliver.getNowPackageDeliver');
      app._postNetWork({
        url: urlStr,
        data: _json,
        success: (resdata) => {
          wx.hideLoading();
          let res = resdata.data;
          if (res.result == 1) {
            this.data.deliverId = res.data.id;
            wx.setStorageSync("deliverId", res.data.id);
            resolve();
          } else {
            wx.showToast({
              title: res.msg,
              duration: 1000,
              icon: 'none'
            });
            reject();
          }
        },
        fail: function (res) {
          wx.hideLoading();
          console.log(res.msg);
        }
      });
    });
  },
  _asyncLocation(){
    return new Promise((resolve, reject) => {
      this._getLocation((mapdata, e)=> {
        let point = app.qqMapTransBMap(
          parseFloat(e.lng),
          parseFloat(e.lat)
        );
        this.data.point = point;
        resolve();
      });
    });
  },
  confirmGoodScreen(e){
    this.setData({
      goods: [],
      goload: true,
      searchScreen: e.detail
    })
    this.cloneGoodScreen();
    this.gotoSearch();
  },
  cloneGoodScreen(){
    this.setData({
      showGoodScreen: false
    })
  }
});
